<template>
  <div class="front-view">
    <!-- 安装包展示 -->
    <div class="package-section">
      <div class="package-header">
        <h2>应用安装包</h2>
        <el-link type="primary" @click="$router.push('/front/package')">更多</el-link>
      </div>
      <el-card shadow="hover">
        <el-collapse>
          <el-collapse-item
            v-for="pkg in packageList"
            :key="pkg.id"
            :title="pkg.fileName"
          >
            <template #title>
              <div class="collapse-title">
                <span>{{ pkg.fileName }}</span>
                <div class="button-group">
                  <el-button type="primary" size="small" @click.stop="handleLocalDownload(pkg.filePath, pkg.fileName)">本地下载</el-button>
                  <el-button type="success" size="small" @click.stop="handleOfficialDownload(pkg.officialUrl)">官网下载</el-button>
                </div>
              </div>
            </template>
            <div class="package-content">
              <img :src="pkg.iconUrl || defaultImage" class="package-icon" @error="handleImageError" />
              <div class="package-info">
                <p><strong>文件名:</strong> {{ pkg.fileName }}</p>
                <p><strong>路径:</strong> {{ pkg.filePath }}</p>
                <p><strong>文件大小:</strong> {{ formatFileSize(pkg.fileSize) }}</p>
                <p><strong>版本号:</strong> {{ pkg.version }}</p>
                <p><strong>后缀名:</strong> {{ pkg.suffix }}</p>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next"
          @current-change="fetchPackages"
          class="pagination"
        />
      </el-card>
    </div>

    <!-- 公告信息 -->
    <div class="announcement-section">
      <div class="announcement-header">
        <h2>公告信息</h2>
        <el-link type="primary" @click="$router.push('/front/announcement')">更多</el-link>
      </div>
      <el-card shadow="hover">
        <el-collapse>
          <el-collapse-item
            v-for="announcement in announcementList"
            :key="announcement.id"
            :title="announcement.title"
          >
            <div>{{ announcement.content }}</div>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useAnnouncementStore } from '@/stores/api/announcement';
import { usePackageStore } from '@/stores/api/package';
import { downloadFile } from '@/stores/util/file';

const router = useRouter();
const announcementStore = useAnnouncementStore();
const packageStore = usePackageStore();

const announcementList = ref([]);
const packageList = ref([]);
const defaultImage = 'https://picsum.photos/64/64?random=0';
const currentPage = ref(1);
const pageSize = 20;
const total = ref(0);

const handleImageError = (e: Event) => {
  (e.target as HTMLImageElement).src = defaultImage;
};

const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

const handleLocalDownload = async (filePath: string, fileName: string) => {
  try {
    await downloadFile(filePath, fileName);
    ElMessage.success('开始下载: ' + fileName);
  } catch (error: any) {
    ElMessage.error('下载失败: ' + error.message);
  }
};

const handleOfficialDownload = (url: string) => {
  if (url) {
    window.open(url, '_blank');
  } else {
    ElMessage.warning('官网链接不可用');
  }
};

const fetchPackages = async () => {
  try {
    const packages = await packageStore.fetchPackages(currentPage.value - 1, pageSize);
    packageList.value = packages;
    total.value = packageStore.total;
  } catch (error: any) {
    ElMessage.error('加载安装包失败: ' + error.message);
  }
};

onMounted(async () => {
  try {
    announcementList.value = await announcementStore.fetchAnnouncements();
    await fetchPackages();
  } catch (error: any) {
    ElMessage.error('加载数据失败: ' + error.message);
  }
});
</script>

<style scoped>
.front-view {
  width: 80%;
  margin: 40px auto 0 auto;
}

.package-section,
.announcement-section {
  margin-bottom: 40px;
}

.package-header,
.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.package-header h2,
.announcement-header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-collapse {
  border: none;
}

.el-collapse-item__header {
  font-size: 16px;
  color: #333;
  padding: 10px 20px;
  background-color: transparent;
  border-bottom: 1px solid #ebeef5;
}

.collapse-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  gap: 10px;
  padding-right: 20px;
}

.package-content {
  display: flex;
  padding: 10px 20px;
}

.package-icon {
  width: 64px;
  height: 64px;
  margin-right: 20px;
  object-fit: cover;
}

.package-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.el-collapse-item__content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>